import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import TextArea from '@/components/TextArea';
import { useAppSelector } from '@/store';
import { editPhotoAction, getProfileAction, updateProfileAction } from '@/store/action/user';
import { profileType1 } from '@/store/reducer/user';
import { removeToken } from '@/utils/storage';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

export default function ProfileEdit() {
  // 控制深入选择框
  const [birthVisible, setBirthVisible] = useState(false);
  // 定义简介输入的初始值
  const [intro, setIntro] = useState('11123');
  // 定义昵称修改输入框的输入值
  const [inputname, setInputname] = useState('');
  // 选择弹出框的类型
  type EditType = 'photo' | 'gender' | 'intro' | 'name';
  const [type, setType] = useState('' as EditType);
  // 3 声明ref
  const InoutRef = useRef<HTMLInputElement>(null);
  // 显示底部弹出框的变量
  const [visible, setVisible] = useState(false);
  // 1. 声明转态，控制右侧弹出层显示
  const [rightVisible, setRightVisible] = useState(false);
  // 获取用户个人资料
  const { profile } = useAppSelector((state) => state.user);
  const dispatch = useDispatch();
  const history = useHistory();

  // 6 调用异步action
  useEffect(() => {
    dispatch(getProfileAction());
  }, [dispatch]);

  // 点击弹出底部框的函数
  const handlebottomPOP = (typeProps: EditType) => {
    setVisible(true);
    setType(typeProps);
  };

  //  监听上传图片 input的onChange事件
  async function handleInput(e: React.ChangeEvent<HTMLInputElement>) {
    // 后台接口要求form-data数据类型，通过new FormData创建，axios自动传给data参数
    const formData = new FormData();
    if (e.target.files) {
      formData.append('photo', e.target.files[0]);
    }
    await dispatch(editPhotoAction(formData));
    Toast.show({ content: '更新头像成功', duration: 1000 });
    setVisible(false);
  }

  // 当弹出框出现时 回显
  useEffect(() => {
    setInputname(profile.name);
    setIntro(profile.intro);
  }, [profile.name, profile.intro]);
  // 处理修改的函数
  const handleUpdate = (profile: Partial<profileType1>) => {
    dispatch(updateProfileAction(profile));
    Toast.show({ content: '更新成功' });
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
  };
  // 处理弹出层的代码提取
  const bottomFn = () => {
    if (type === 'photo') {
      return (
        <>
          <div className="list-item" onClick={() => InoutRef.current?.click()}>
            拍照
          </div>
          <div className="list-item" onClick={() => InoutRef.current?.click()}>
            本地选择
          </div>
        </>
      );
    }
    if (type === 'gender') {
      return (
        <>
          <div
            className="list-item"
            onClick={() => {
              handleUpdate({ gender: 0 });
            }}
          >
            男
          </div>
          <div
            className="list-item"
            onClick={() => {
              handleUpdate({ gender: 1 });
            }}
          >
            女
          </div>
        </>
      );
    }
  };
  // 退出弹出层 返回个人信息
  const handleBack = () => {
    setRightVisible(false);
    // 返回时没修改再重新回显正确的值
    if (type === 'name') setInputname(profile.name);
    if (type === 'intro') setIntro(profile.intro);
  };

  // 输入框键盘事件
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      // 回车之后提交修改
      handleUpdate({ name: inputname });
    }
  };

  // 5. 根据editType渲染不同的内容
  function renderRight() {
    // 提交属性配置
    let value = '';
    if (type === 'intro') value = intro;
    if (type === 'name') value = inputname;
    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span className="submit-btn" onClick={() => handleUpdate({ [type]: value })}>
              提交
            </span>
          }
        >
          编辑
          {type === 'intro' && '简介'}
          {type === 'name' && '昵称'}
        </NavBar>
        <div className="edit-content">
          {type === 'intro' && (
            <TextArea
              autoFocus={true}
              // value 后台可能会返回null
              value={intro || ''}
              onChange={(e) => setIntro(e.target.value)}
            />
          )}
          {type === 'name' && (
            <Input
              className="edit-input"
              autoFocus
              value={inputname}
              onChange={(e) => setInputname(e.target.value)}
              onKeyDown={handleKeyDown}
            />
          )}
        </div>
      </>
    );
  }
  // 退出登录
  const handleLetout = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '亲，真的要退出吗',
      onConfirm: () => {
        // 清除token
        removeToken();
        // 跳转路由
        history.push('/login');
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => handlebottomPOP('photo')}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => {
                setType('name');
                setRightVisible(true);
              }}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro}</span>}
              onClick={() => {
                setType('intro');
                setRightVisible(true);
              }}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 1 ? '女' : '男'}
              onClick={() => handlebottomPOP('gender')}
            >
              性别
            </List.Item>
            <List.Item arrow extra={profile.birthday} onClick={() => setBirthVisible(true)}>
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input className="avatar-upload" type="file" />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLetout}>
            退出登录
          </button>
        </div>
      </div>
      {/* 生日选择 */}
      <DatePicker
        title="时间选择"
        visible={birthVisible}
        onClose={() => {
          setBirthVisible(false);
        }}
        min={new Date('1900-01-01')}
        max={new Date()}
        value={new Date(profile.birthday)}
        onConfirm={(val) => {
          handleUpdate({ birthday: dayjs(val).format('YYYY-MM-DD') });
        }}
      />

      {/* 底部弹出层 */}
      <Popup
        visible={visible}
        onMaskClick={() => setVisible(false)}
        position="bottom"
        bodyClassName="popup-bottom-list"
      >
        {/* 建议jsx不要放处理逻辑的代码 */}
        {bottomFn()}

        <div className="list-item">取消</div>
      </Popup>
      {/* 右边弹出框 */}
      <Popup
        position="right"
        bodyClassName="popup-right"
        visible={rightVisible}
        // 6. 点击关闭
        onMaskClick={() => setRightVisible(false)}
        // 5. destroyOnClose可以通知antd，卸载内容
        destroyOnClose
      >
        {renderRight()}
      </Popup>

      {/* 1 上传图片 原生 */}
      <input type="file" onChange={(e) => handleInput(e)} ref={InoutRef} />
    </div>
  );
}
